//
//  CZMainTabBarController.swift
//  iOSWeibo10
//
//  Created by itcast on 16/5/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZMainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        tabBar.tintColor = UIColor.orangeColor()
        
        // 1.定义闭包
        let compseCallback = { () -> () in
            // 用户没有登录
            if !CZUserAccountViewModel.sharedInstance.isUserLogin {
                // Modal出授权控制器
                let oauthVC = CZOauthViewController()
                
                let nav = UINavigationController(rootViewController: oauthVC)
                self.presentViewController(nav, animated: true, completion: nil)
            } else {
                // Modal出控制器
                // 创建发微博控制器
                let composeVC = CZComposeViewController()
                let nav = UINavigationController(rootViewController: composeVC)
                
                self.presentViewController(nav, animated: true, completion: nil)
            }
        }
        
        let mainTabBar = CZMainTabBar()
        
        // 2.传递闭包
        mainTabBar.composeCallback = compseCallback
        
        // get,只读的属性,没有set方法, = 赋值调用的是set放法,只读属性没有了set就不能用=直接赋值
        // 使用KVC,KVC会先去找set方法如果没有set方法会找_tabBar成员变量,KVC使用运行时
//        tabBar = mainTabBar
        setValue(mainTabBar, forKey: "tabBar")
        
        setupChilderViewController()
    }

    /// 设置tabbar子控制器
    func setupChilderViewController() {
        // 首页
        let homeVC = CZHomeViewController()
        addChildViewController(homeVC, title: "首页", imageName: "tabbar_home")
        
        // 消息
        let messageVC = CZMessageViewController()
        addChildViewController(messageVC, title: "消息", imageName: "tabbar_message_center")
        
        // 发现
        let discoveryVC = CZDiscoveryViewController()
        addChildViewController(discoveryVC, title: "发现", imageName: "tabbar_discover")
        
        // 我
        let profileVC = CZProfileViewController()
        addChildViewController(profileVC, title: "我", imageName: "tabbar_profile")
    }
    
    /// 添加子控制器,设置标题和图片名称,并且包装导航控制器
    func addChildViewController(controller: UIViewController, title: String, imageName: String) {
        // 设置标题
        controller.title = title
        // 设置tabbar图片
        controller.tabBarItem.image = UIImage(named: imageName)
        // 设置高亮图片
        controller.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        // 设置文字选中的颜色
        controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orangeColor()], forState: UIControlState.Selected)
        
        // 包装导航控制器
        self.addChildViewController(UINavigationController(rootViewController: controller))
    }
}
